package com.heima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.feigns.article.ArticleFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.constants.FollowBehaviorConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.FollowBehaviorDto;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserFan;
import com.heima.model.user.pojos.ApUserFollow;
import com.heima.user.mapper.ApUserFanMapper;
import com.heima.user.mapper.ApUserFollowMapper;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserRelationService;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @Description:
 * @Version: V1.0
 */
@Service
public class ApUserRelationServiceImpl implements ApUserRelationService {


    @Autowired
    ArticleFeign articleFeign;

    @Autowired
    KafkaTemplate kafkaTemplate;

    /**
     * 用户关注/取消关注
     * @param dto
     * @return
     */
    @Override
    public ResponseResult follow(UserRelationDto dto) {
        //1 参数检查
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (dto.getAuthorId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2 远程调用feign 查询文章对应的作者信息
        ApAuthor apAuthor = articleFeign.findById(dto.getAuthorId());
        if (apAuthor == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "关注作者不存在");
        }
        // 得到作者对应的 apUser
        Integer followUserId = apAuthor.getUserId();
        if (followUserId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "关注作者不存在");
        }

        //3 得到当前登录的用户（普通用户）
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //4 关注/取消关注
        if (dto.getOperation() == 0) {
            //关注
            return followByUserId(user.getId(), followUserId, dto.getArticleId());
        }else {
            return followCancelByUserId(user.getId(), followUserId);
        }
    }

    @Autowired
    ApUserFollowMapper apUserFollowMapper;

    @Autowired
    ApUserMapper apUserMapper;

    @Autowired
    ApUserFanMapper apUserFanMapper;

    /**
     * 取消关注
     * @param userId 当前登录用户id
     * @param followUserId 关注的作者对应的用户id
     * @return
     */
    private ResponseResult followCancelByUserId(Integer userId, Integer followUserId) {
        //5 取消关注
        //5.1 删除我的关注
        apUserFollowMapper.delete( Wrappers.<ApUserFollow>lambdaQuery()
                .eq(ApUserFollow::getUserId, userId).eq(ApUserFollow::getFollowId, followUserId));

        //5.2 作者对应的粉丝
        apUserFanMapper.delete(Wrappers.<ApUserFan>lambdaQuery()
                .eq(ApUserFan::getUserId, followUserId).eq(ApUserFan::getFansId, userId));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    /**
     * 关注
     * @param userId  当前登录用户
     * @param followUserId 关注的作者对应的用户id
     * @param articleId 文章id
     * @return
     */
    private ResponseResult followByUserId(Integer userId, Integer followUserId, Long articleId) {
        // 我的关注
        if (userId.intValue() == followUserId.intValue()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"不能关注自己");
        }
        ApUserFollow apUserFollow = apUserFollowMapper.selectOne(Wrappers.<ApUserFollow>lambdaQuery()
                .eq(ApUserFollow::getUserId, userId).eq(ApUserFollow::getFollowId, followUserId));
        if (apUserFollow != null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"无需重复关注");
        }
        //4.1 保存关注数据  -- 先查
        apUserFollow = new ApUserFollow();
        apUserFollow.setUserId(userId);
        apUserFollow.setFollowId(followUserId);
        ApUser followUser = apUserMapper.selectById(followUserId);
        apUserFollow.setFollowName(followUser.getName());
        apUserFollow.setLevel((short) 1);
        apUserFollow.setIsNotice(true);
        apUserFollow.setCreatedTime(new Date());
        apUserFollowMapper.insert(apUserFollow);

        //4.2 保存文章作者对应的apUser 的粉丝  先查
        ApUserFan apUserFan = apUserFanMapper.selectOne(Wrappers.<ApUserFan>lambdaQuery()
                .eq(ApUserFan::getUserId, followUserId).eq(ApUserFan::getFansId, userId));
        if (apUserFan != null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"已存在该粉丝");
        }
        apUserFan = new ApUserFan();
        apUserFan.setUserId(followUserId);
        apUserFan.setFansId(userId.longValue());

        ApUser apUser = apUserMapper.selectById(userId);
        apUserFan.setFansName(apUser.getName());
        apUserFan.setLevel((short) 0);
        apUserFan.setCreatedTime(new Date());
        apUserFan.setIsDisplay(true);
        apUserFan.setIsShieldLetter(false);
        apUserFan.setIsShieldComment(false);
        apUserFanMapper.insert(apUserFan);

        //  异步记录行为
        FollowBehaviorDto dto = new FollowBehaviorDto(articleId, followUserId, userId);
        kafkaTemplate.send(FollowBehaviorConstants.FOLLOW_BEHAVIOR_TOPIC, JSON.toJSONString(dto));


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
